<template>
  <div class="bgc-default pad-20" v-loading="listLoading" element-loading-text="加载中">
    
    <!-- 平台类型 -->
    <third-platform-head :showTaoBaoIcon="false"
      :showDouYinIcon="false"
      :showKuaiShouIcon="false"
      :showPinDuoDuoIcon="false"
      :showTmallIcon="false"
      :showAmazonIcon="false"
      :defaultPlatformType="platformType"
      @platformTypeChange="platformTypeChange">
    </third-platform-head>

    <div class="bg-color-white mar-t-15 pad-l-20 pad-r-20 pad-t-20">
      <!-- 店铺块 -->
      <div>
        <label>选择店铺：</label>
        <el-select v-model="selectedShopId" placeholder="选择店铺" @change="doChangeShop">
          <el-option v-for="item in shopList" 
            :key="item.shopId" 
            :label="item.shopName" 
            :value="item.shopId">
          </el-option>
        </el-select>

        <el-button class="mar-l-20" type="primary" @click="doSyncGoods()">同步商品</el-button>
      </div>

      <el-divider></el-divider>

      <!--顶部搜索 -->
      <div class="top-operate pad-l-10 pad-r-10">
        <!-- 第二行 -->
        <div>
          <div class="inline-flex">
            <el-select v-model="textCol" class="width-120">
              <el-option label="商品名称" value="externalGoodsTitle"></el-option>
            </el-select>
            <el-input v-model="textValue" placeholder="请输入内容" class="width-200"></el-input>
          </div>
          <div class="inline-flex">
            <el-select v-model="timeCol" class="width-120 mar-l-20">
              <el-option label="同步时间" value="syncTime"></el-option>
            </el-select>
            <el-date-picker v-model="timeValue"
              type="datetimerange"
              class="search-input-5"
              range-separator="至"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
          <div class="inline-flex">
            <span class="mar-l-20">加入状态：</span>
            <el-select v-model="defaultQuery.joinStatus" class="width-120" clearable>
              <el-option label="未加入" value=0></el-option>
              <el-option label="已加入" value=1></el-option>
            </el-select>
          </div>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button plain @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="dataList">
          <el-table-column width="320px" label="商品名称" fixed="left">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p">
                <label><img :src="scope.row.externalGoodsImage" class="t-goods-pic"></label>
                <div class="font-14 pad-l-10 v-align-h height-65">
                  <div class="goods-title">
                    <div class="line-2">
                      <span>{{ scope.row.externalGoodsTitle }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="120px" label="商品价格" prop="externalGoodsPrice" align="center">
          </el-table-column>
          <el-table-column min-width="120px" label="加入状态" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.joinStatus === 0 ? '未加入' : '已加入' }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="180px" label="同步时间" prop="syncTime" align="center">
          </el-table-column>
          <el-table-column min-width="120px" label="操作" align="right">
            <template slot-scope="scope">
              <el-button type="text" size="medium" class="table-btn" @click="doLinkDetail(scope.row)">商品详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

  </div>
</template>

<script>
  import { getDictByGroupName } from '@/api/common/common'
  import { listThirdShop } from '@/api/user/third-shop'
  import {
    pagingThirdGoodsSyncHistory
  } from '@/api/third/thirdGoodsSyncHistory'

  import thirdAuth from '../components/third-auth'
  import thirdPlatformHead from '../components/third-platform-head'
  
  export default {
    components: {
      thirdPlatformHead
    },
    mixins: [thirdAuth],
    data() {
      return {
        // 文本model
        textCol: 'externalGoodsTitle',
        textValue: '',
        // 时间model
        timeCol: 'syncTime',
        timeValue: [],
        // 默认条件
        defaultQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: '',
          joinStatus: ''
        },
        // 查询条件
        searchListQuery: {},
        // 数据字典
        dict: {
          platformType: {}
        },
        // 店铺id
        selectedShopId: '',
        // 平台类型
        platformType: 7,
        // 店铺集合
        shopList: [],
        total: 0,
        dataList: [],
        listLoading: false
      }
    },
    // 初始化页面
    created() {
      Object.assign(this.searchListQuery, this.defaultQuery)
      getDictByGroupName('ThirdOrderDTO.platformType').then(response => {
        Object.assign(this.dict, response.data)
      })
    },
    methods: {
      // 获取商品列表
      initList() {
        if (!this.selectedShopId) {
          this.dataList = []
          this.total = 0
          return
        }
        this.searchQuery()
        this.listLoading = true
        pagingThirdGoodsSyncHistory(this.searchListQuery).then(response => {
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
          this.listLoading = false
        })
      },
      // 平台类型切换事件
      platformTypeChange(platformType) {
        this.platformType = platformType
        this.selectedShopId = ''
        this.initListThirdShop()
      },
      // 店铺切换事件
      doChangeShop() {
        this.doResetSearch()
      },
      // tab切换事件
      doChangeTab() {
        this.searchListQuery.currentPage = 1
        this.doResetSearch()
      },
      // 获取第三方店铺列表
      initListThirdShop() {
        const params = {
          enterpriseId: this.getEnterpriseId(),
          memberId: this.getMemberId(),
          platformType: this.platformType
        }
        listThirdShop(params).then(response => {
          if (response.isError) return
          this.shopList = response.data
          if (response.data.length > 0) {
            this.selectedShopId = response.data[0].shopId
          }
          this.doResetSearch()
        })
      },
      // 设置查询条件
      searchQuery() {
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage

        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.dateColumn = this.timeCol
        this.searchListQuery.startDate = (this.timeValue && this.timeValue.length > 0) ? this.timeValue[0] : ''
        this.searchListQuery.endDate = (this.timeValue && this.timeValue.length > 1) ? this.timeValue[1] : ''
        this.searchListQuery.shopId = this.selectedShopId
        this.searchListQuery.platformType = this.platformType
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.timeCol = originData.timeCol
        this.timeValue = originData.timeValue
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 同步商品事件
      doSyncGoods() {
        const redirectUrl = '/#/' + (this.getMemberId() ? 'shop' : 'channel') + '/third-goods-sync/index?platformType=' + this.platformType
        this.checkAccessToken(this.platformType, this.selectedShopId, redirectUrl, true).then(response => {
          if (response) {
            const platformName = this.dict.platformType[this.platformType]
            const msg = '同步商品将会拉取' + platformName + '商家后台可用的商品，商品越多耗时越久，确定要同步吗？'
            this.$confirm(msg, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              const params = {
                enterpriseId: this.getEnterpriseId(),
                shopId: this.selectedShopId,
                platformType: this.platformType
              }
              this.$bus.$emit('asyncHandle', '300010', params, () => {
                this.doSearch()
              })
            }).catch(() => {
              this.$message({ type: 'info', message: '已取消' })
            })
          }
        })
      },
      // 查看详情事件
      doLinkDetail(row) {
        const queryParam = {
          fromListPage: row.platformType === 7 ? '31' : '30'
        }
        if (row.goodsId) {
          queryParam.goodsId = row.goodsId
        } else {
          queryParam.goodsSyncHistoryId = row.goodsSyncHistoryId
        }
        const routeData = this.$router.resolve({
          path: '/goods/edit/index',
          query: queryParam
        })
        window.open(routeData.href, row.goodsId ? row.goodsId : row.goodsSyncHistoryId)
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .goods-title {
    color: #155bd4;
    line-height: 1.2;
  }
</style>
